<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------

/**
 * Think 基础函数库
 * @category   Think
 * @package  Common
 * @author   liu21st <liu21st@gmail.com>
 */

/**
 * 获取输入参数 支持过滤和默认值
 * 使用方法:
 * <code>
 * I('id',0); 获取id参数 自动判断get或者post
 * I('post.name','','htmlspecialchars'); 获取$_POST['name']
 * I('get.'); 获取$_GET
 * </code> 
 * @param string $name 变量的名称 支持指定类型
 * @param mixed $default 不存在的时候默认值
 * @param mixed $filter 参数过滤方法
 * @return mixed
 */
function I($name,$default='',$filter='') {
    if(strpos($name,'.')) { // 指定参数来源
        list($method,$name) =   explode('.',$name);
    }else{ // 默认为自动判断
        $method =   'param';
    }
    switch(strtolower($method)) {
        case 'get'     :   $input =& $_GET;break;
        case 'post'    :   $input =& $_POST;break;
        case 'put'     :   parse_str(file_get_contents('php://input'), $input);break;
        case 'param'   :  
            switch($_SERVER['REQUEST_METHOD']) {
                case 'POST':
                    $input  =  $_POST;
                    break;
                case 'PUT':
                    parse_str(file_get_contents('php://input'), $input);
                    break;
                default:
                    $input  =  $_GET;
            }
            if(C('VAR_URL_PARAMS')){
                $params = $_GET[C('VAR_URL_PARAMS')];
                $input  =   array_merge($input,$params);
            }
            break;
        case 'request' :   $input =& $_REQUEST;   break;
        case 'session' :   $input =& $_SESSION;   break;
        case 'cookie'  :   $input =& $_COOKIE;    break;
        case 'server'  :   $input =& $_SERVER;    break;
        case 'globals' :   $input =& $GLOBALS;    break;
        default:
            return NULL;
    }
    // 全局过滤
    // array_walk_recursive($input,'filter_exp');
    if(C('VAR_FILTERS')) {
        $_filters    =   explode(',',C('VAR_FILTERS'));
        foreach($_filters as $_filter){
            // 全局参数过滤
            array_walk_recursive($input,$_filter);
        }
    }
    if(empty($name)) { // 获取全部变量
        $data       =   $input; 
    }elseif(isset($input[$name])) { // 取值操作
        $data       =	$input[$name];
        $filters    =   isset($filter)?$filter:C('DEFAULT_FILTER');
        if($filters) {
            $filters    =   explode(',',$filters);
            foreach($filters as $filter){
                if(function_exists($filter)) {
                    $data   =   is_array($data)?array_map($filter,$data):$filter($data); // 参数过滤
                }else{
                    $data   =   filter_var($data,is_int($filter)?$filter:filter_id($filter));
                    if(false === $data) {
                        return	 isset($default)?$default:NULL;
                    }
                }
            }
        }
    }else{ // 变量默认值
        $data       =	 isset($default)?$default:NULL;
    }
    return $data;
}


/**
 * 记录和统计时间（微秒）和内存使用情况
 * 使用方法:
 * <code>
 * G('begin'); // 记录开始标记位
 * // ... 区间运行代码
 * G('end'); // 记录结束标签位
 * echo G('begin','end',6); // 统计区间运行时间 精确到小数后6位
 * echo G('begin','end','m'); // 统计区间内存使用情况
 * 如果end标记位没有定义，则会自动以当前作为标记位
 * 其中统计内存使用需要 MEMORY_LIMIT_ON 常量为true才有效
 * </code>
 * @param string $start 开始标签
 * @param string $end 结束标签
 * @param integer|string $dec 小数位或者m 
 * @return mixed
 */
function G($start,$end='',$dec=4) {
    static $_info       =   array();
    static $_mem        =   array();
    if(is_float($end)) { // 记录时间
        $_info[$start]  =   $end;
    }elseif(!empty($end)){ // 统计时间和内存使用
        if(!isset($_info[$end])) $_info[$end]       =  microtime(TRUE);
        if(MEMORY_LIMIT_ON && $dec=='m'){
            if(!isset($_mem[$end])) $_mem[$end]     =  memory_get_usage();
            return number_format(($_mem[$end]-$_mem[$start])/1024);          
        }else{
            return number_format(($_info[$end]-$_info[$start]),$dec);
        }       
            
    }else{ // 记录时间和内存使用
        $_info[$start]  =  microtime(TRUE);
        if(MEMORY_LIMIT_ON) $_mem[$start]           =  memory_get_usage();
    }
}

/**
 * 设置和获取统计数据
 * 使用方法:
 * <code>
 * N('db',1); // 记录数据库操作次数
 * N('read',1); // 记录读取次数
 * echo N('db'); // 获取当前页面数据库的所有操作次数
 * echo N('read'); // 获取当前页面读取次数
 * </code> 
 * @param string $key 标识位置
 * @param integer $step 步进值
 * @return mixed
 */
function N($key, $step=0,$save=false) {
    static $_num    = array();
    if (!isset($_num[$key])) {
        $_num[$key] = (false !== $save)? S('N_'.$key) :  0;
    }
    if (empty($step))
        return $_num[$key];
    else
        $_num[$key] = $_num[$key] + (int) $step;
    if(false !== $save){ // 保存结果
        S('N_'.$key,$_num[$key],$save);
    }
}

/**
 * 字符串命名风格转换
 * type 0 将Java风格转换为C的风格 1 将C风格转换为Java的风格
 * @param string $name 字符串
 * @param integer $type 转换类型
 * @return string
 */
function parse_name($name, $type=0) {
    if ($type) {
        return ucfirst(preg_replace("/_([a-zA-Z])/e", "strtoupper('\\1')", $name));
    } else {
        return strtolower(trim(preg_replace("/[A-Z]/", "_\\0", $name), "_"));
    }
}

/**
 * 优化的require_once
 * @param string $filename 文件地址
 * @return boolean
 */
function require_cache($filename) {
    static $_importFiles = array();
    if (!isset($_importFiles[$filename])) {
        if (file_exists_case($filename)) {
            require $filename;
            $_importFiles[$filename] = true;
        } else {
            $_importFiles[$filename] = false;
        }
    }
    return $_importFiles[$filename];
}

/**
 * 批量导入文件 成功则返回
 * @param array $array 文件数组
 * @param boolean $return 加载成功后是否返回
 * @return boolean
 */
function require_array($array,$return=false){
    foreach ($array as $file){
        if (require_cache($file) && $return) return true;
    }
    if($return) return false;
}

/**
 * 区分大小写的文件存在判断
 * @param string $filename 文件地址
 * @return boolean
 */
function file_exists_case($filename) {
    if (is_file($filename)) {
        if (IS_WIN && C('APP_FILE_CASE')) {
            if (basename(realpath($filename)) != basename($filename))
                return false;
        }
        return true;
    }
    return false;
}

/**
 * 导入所需的类库 同java的Import 本函数有缓存功能
 * @param string $class 类库命名空间字符串
 * @param string $baseUrl 起始路径
 * @param string $ext 导入的文件扩展名
 * @return boolean
 */
function import($class, $baseUrl = '', $ext='.class.php') {
    static $_file = array();
    $class = str_replace(array('.', '#'), array('/', '.'), $class);
    if ('' === $baseUrl && false === strpos($class, '/')) {
        // 检查别名导入
        return alias_import($class);
    }
    if (isset($_file[$class . $baseUrl]))
        return true;
    else
        $_file[$class . $baseUrl] = true;
    $class_strut     = explode('/', $class);
    if (empty($baseUrl)) {
        $libPath    =   defined('BASE_LIB_PATH')?BASE_LIB_PATH:LIB_PATH;
        if ('@' == $class_strut[0] || APP_NAME == $class_strut[0]) {
            //加载当前项目应用类库
            $baseUrl = dirname($libPath);
            $class   = substr_replace($class, basename($libPath).'/', 0, strlen($class_strut[0]) + 1);
        }elseif ('think' == strtolower($class_strut[0])){ // think 官方基类库
            $baseUrl = CORE_PATH;
            $class   = substr($class,6);
        }elseif (in_array(strtolower($class_strut[0]), array('org', 'com'))) {
            // org 第三方公共类库 com 企业公共类库
            $baseUrl = LIBRARY_PATH;
        }else { // 加载其他项目应用类库
            $class   = substr_replace($class, '', 0, strlen($class_strut[0]) + 1);
            $baseUrl = APP_PATH . '../' . $class_strut[0] . '/'.basename($libPath).'/';
        }
    }
    if (substr($baseUrl, -1) != '/')
        $baseUrl    .= '/';
    $classfile       = $baseUrl . $class . $ext;
    if (!class_exists(basename($class),false)) {
        // 如果类不存在 则导入类库文件
        return require_cache($classfile);
    }
}

/**
 * 基于命名空间方式导入函数库
 * load('@.Util.Array')
 * @param string $name 函数库命名空间字符串
 * @param string $baseUrl 起始路径
 * @param string $ext 导入的文件扩展名
 * @return void
 */
function load($name, $baseUrl='', $ext='.php') {
    $name = str_replace(array('.', '#'), array('/', '.'), $name);
    if (empty($baseUrl)) {
        if (0 === strpos($name, '@/')) {
            //加载当前项目函数库
            $baseUrl    = COMMON_PATH;
            $name       = substr($name, 2);
        } else {
            //加载ThinkPHP 系统函数库
            $baseUrl    = EXTEND_PATH . 'Function/';
        }
    }
    if (substr($baseUrl, -1) != '/')
        $baseUrl       .= '/';
    require_cache($baseUrl . $name . $ext);
}

/**
 * 快速导入第三方框架类库 所有第三方框架的类库文件统一放到 系统的Vendor目录下面
 * @param string $class 类库
 * @param string $baseUrl 基础目录
 * @param string $ext 类库后缀 
 * @return boolean
 */
function vendor($class, $baseUrl = '', $ext='.php') {
    if (empty($baseUrl))
        $baseUrl = VENDOR_PATH;
    return import($class, $baseUrl, $ext);
}

/**
 * 快速定义和导入别名 支持批量定义
 * @param string|array $alias 类库别名
 * @param string $classfile 对应类库
 * @return boolean
 */
function alias_import($alias, $classfile='') {
    static $_alias = array();
    if (is_string($alias)) {
        if(isset($_alias[$alias])) {
            return require_cache($_alias[$alias]);
        }elseif ('' !== $classfile) {
            // 定义别名导入
            $_alias[$alias] = $classfile;
            return;
        }
    }elseif (is_array($alias)) {
        $_alias   =  array_merge($_alias,$alias);
        return;
    }
    return false;
}

/**
 * D函数用于实例化Model 格式 项目://分组/模块
 * @param string $name Model资源地址
 * @param string $layer 业务层名称
 * @return Model
 */
function D($name='',$layer='') {
    if(empty($name)) return new Model;
    static $_model  =   array();
    $layer          =   $layer?$layer:C('DEFAULT_M_LAYER');
    if(strpos($name,'://')) {// 指定项目
        $name       =   str_replace('://','/'.$layer.'/',$name);
    }else{
        $name       =   C('DEFAULT_APP').'/'.$layer.'/'.$name;
    }
    if(isset($_model[$name]))   return $_model[$name];
    $path           =   explode('/',$name);
    if(count($path)>3 && 1 == C('APP_GROUP_MODE')) { // 独立分组
        $baseUrl    =   $path[0]== '@' ? dirname(BASE_LIB_PATH) : APP_PATH.'../'.$path[0].'/'.C('APP_GROUP_PATH').'/';
        import($path[2].'/'.$path[1].'/'.$path[3].$layer,$baseUrl);
    }else{
        import($name.$layer);
    } 
    $class          =   basename($name.$layer);
    if(class_exists($class)) {
        $model      =   new $class(basename($name));
    }else {
        $model      =   new Model(basename($name));
    }
    $_model[$name]  =  $model;
    return $model;
}

/**
 * M函数用于实例化一个没有模型文件的Model
 * @param string $name Model名称 支持指定基础模型 例如 MongoModel:User
 * @param string $tablePrefix 表前缀
 * @param mixed $connection 数据库连接信息
 * @return Model
 */
function M($name='', $tablePrefix='',$connection='') {
    static $_model  = array();
    if(strpos($name,':')) {
        list($class,$name)    =  explode(':',$name);
    }else{
        $class      =   'Model';
    }
    $guid           =   $tablePrefix . $name . '_' . $class;
    if (!isset($_model[$guid]))
        $_model[$guid] = new $class($name,$tablePrefix,$connection);
    return $_model[$guid];
}

/**
 * A函数用于实例化Action 格式：[项目://][分组/]模块
 * @param string $name Action资源地址
 * @param string $layer 控制层名称
 * @param boolean $common 是否公共目录
 * @return Action|false
 */
function A($name,$layer='',$common=false) {
    static $_action = array();
    $layer      =   $layer?$layer:C('DEFAULT_C_LAYER');
    if(strpos($name,'://')) {// 指定项目
        $name   =  str_replace('://','/'.$layer.'/',$name);
    }else{
        $name   =  '@/'.$layer.'/'.$name;
    }
    if(isset($_action[$name]))  return $_action[$name];
    $path           =   explode('/',$name);
    if(count($path)>3 && 1 == C('APP_GROUP_MODE')) { // 独立分组
        $baseUrl    =   $path[0]== '@' ? dirname(BASE_LIB_PATH) : APP_PATH.'../'.$path[0].'/'.C('APP_GROUP_PATH').'/';
        import($path[2].'/'.$path[1].'/'.$path[3].$layer,$baseUrl);
    }elseif($common) { // 加载公共类库目录
        import(str_replace('@/','',$name).$layer,LIB_PATH);
    }else{
        import($name.$layer);
    }
    $class      =   basename($name.$layer);
    if(class_exists($class,false)) {
        $action             =   new $class();
        $_action[$name]     =   $action;
        return $action;
    }else {
        return false;
    }
}

/**
 * 远程调用模块的操作方法 URL 参数格式 [项目://][分组/]模块/操作
 * @param string $url 调用地址
 * @param string|array $vars 调用参数 支持字符串和数组 
 * @param string $layer 要调用的控制层名称
 * @return mixed
 */
function R($url,$vars=array(),$layer='') {
    $info   =   pathinfo($url);
    $action =   $info['basename'];
    $module =   $info['dirname'];
    $class  =   A($module,$layer);
    if($class){
        if(is_string($vars)) {
            parse_str($vars,$vars);
        }
        return call_user_func_array(array(&$class,$action.C('ACTION_SUFFIX')),$vars);
    }else{
        return false;
    }
}

/**
 * 获取和设置语言定义(不区分大小写)
 * @param string|array $name 语言变量
 * @param string $value 语言值
 * @return mixed
 */
function L($name=null, $value=null) {
    static $_lang = array();
    // 空参数返回所有定义
    if (empty($name))
        return $_lang;
    // 判断语言获取(或设置)
    // 若不存在,直接返回全大写$name
    if (is_string($name)) {
        $name = strtoupper($name);
        if (is_null($value))
            return isset($_lang[$name]) ? $_lang[$name] : $name;
        $_lang[$name] = $value; // 语言定义
        return;
    }
    // 批量定义
    if (is_array($name))
        $_lang = array_merge($_lang, array_change_key_case($name, CASE_UPPER));
    return;
}

/**
 * 获取和设置配置参数 支持批量定义
 * @param string|array $name 配置变量
 * @param mixed $value 配置值
 * @return mixed
 */
function C($name=null, $value=null) {
    static $_config = array();
    // 无参数时获取所有
    if (empty($name)) {
        if(!empty($value) && $array = S('c_'.$value)) {
            $_config = array_merge($_config, array_change_key_case($array));
        }
        return $_config;
    }
    // 优先执行设置获取或赋值
    if (is_string($name)) {
        if (!strpos($name, '.')) {
            $name = strtolower($name);
            if (is_null($value))
                return isset($_config[$name]) ? $_config[$name] : null;
            $_config[$name] = $value;
            return;
        }
        // 二维数组设置和获取支持
        $name = explode('.', $name);
        $name[0]   =  strtolower($name[0]);
        if (is_null($value))
            return isset($_config[$name[0]][$name[1]]) ? $_config[$name[0]][$name[1]] : null;
        $_config[$name[0]][$name[1]] = $value;
        return;
    }
    // 批量设置
    if (is_array($name)){
        $_config = array_merge($_config, array_change_key_case($name));
        if(!empty($value)) {// 保存配置值
            S('c_'.$value,$_config);
        }
        return;
    }
    return null; // 避免非法参数
}

/**
 * 处理标签扩展
 * @param string $tag 标签名称
 * @param mixed $params 传入参数
 * @return mixed
 */
function tag($tag, &$params=NULL) {
    // 系统标签扩展
    $extends    = C('extends.' . $tag);
    // 应用标签扩展
    $tags       = C('tags.' . $tag);
    if (!empty($tags)) {
        if(empty($tags['_overlay']) && !empty($extends)) { // 合并扩展
            $tags = array_unique(array_merge($extends,$tags));
        }elseif(isset($tags['_overlay'])){ // 通过设置 '_overlay'=>1 覆盖系统标签
            unset($tags['_overlay']);
        }
    }elseif(!empty($extends)) {
        $tags = $extends;
    }
    if($tags) {
        if(APP_DEBUG) {
            G($tag.'Start');
            trace('[ '.$tag.' ] --START--','','INFO');
        }
        // 执行扩展
        foreach ($tags as $key=>$name) {
            if(!is_int($key)) { // 指定行为类的完整路径 用于模式扩展
                $name   = $key;
            }
            B($name, $params);
        }
        if(APP_DEBUG) { // 记录行为的执行日志
            trace('[ '.$tag.' ] --END-- [ RunTime:'.G($tag.'Start',$tag.'End',6).'s ]','','INFO');
        }
    }else{ // 未执行任何行为 返回false
        return false;
    }
}

/**
 * 动态添加行为扩展到某个标签
 * @param string $tag 标签名称
 * @param string $behavior 行为名称
 * @param string $path 行为路径 
 * @return void
 */
function add_tag_behavior($tag,$behavior,$path='') {
    $array      =  C('tags.'.$tag);
    if(!$array) {
        $array  =  array();
    }
    if($path) {
        $array[$behavior] = $path;
    }else{
        $array[] =  $behavior;
    }
    C('tags.'.$tag,$array);
}

/**
 * 执行某个行为
 * @param string $name 行为名称
 * @param Mixed $params 传人的参数
 * @return void
 */
function B($name, &$params=NULL) {
    $class      = $name.'Behavior';
    if(APP_DEBUG) {
        G('behaviorStart');
    }
    $behavior   = new $class();
    $behavior->run($params);
    if(APP_DEBUG) { // 记录行为的执行日志
        G('behaviorEnd');
        trace('Run '.$name.' Behavior [ RunTime:'.G('behaviorStart','behaviorEnd',6).'s ]','','INFO');
    }
}

/**
 * 去除代码中的空白和注释
 * @param string $content 代码内容
 * @return string
 */
function strip_whitespace($content) {
    $stripStr   = '';
    //分析php源码
    $tokens     = token_get_all($content);
    $last_space = false;
    for ($i = 0, $j = count($tokens); $i < $j; $i++) {
        if (is_string($tokens[$i])) {
            $last_space = false;
            $stripStr  .= $tokens[$i];
        } else {
            switch ($tokens[$i][0]) {
                //过滤各种PHP注释
                case T_COMMENT:
                case T_DOC_COMMENT:
                    break;
                //过滤空格
                case T_WHITESPACE:
                    if (!$last_space) {
                        $stripStr  .= ' ';
                        $last_space = true;
                    }
                    break;
                case T_START_HEREDOC:
                    $stripStr .= "<<<THINK\n";
                    break;
                case T_END_HEREDOC:
                    $stripStr .= "THINK;\n";
                    for($k = $i+1; $k < $j; $k++) {
                        if(is_string($tokens[$k]) && $tokens[$k] == ';') {
                            $i = $k;
                            break;
                        } else if($tokens[$k][0] == T_CLOSE_TAG) {
                            break;
                        }
                    }
                    break;
                default:
                    $last_space = false;
                    $stripStr  .= $tokens[$i][1];
            }
        }
    }
    return $stripStr;
}

//[RUNTIME]
// 编译文件
function compile($filename) {
    $content        = file_get_contents($filename);
    // 替换预编译指令
    $content        = preg_replace('/\/\/\[RUNTIME\](.*?)\/\/\[\/RUNTIME\]/s', '', $content);
    $content        = substr(trim($content), 5);
    if ('?>' == substr($content, -2))
        $content    = substr($content, 0, -2);
    return $content;
}

// 根据数组生成常量定义
function array_define($array,$check=true) {
    $content = "\n";
    foreach ($array as $key => $val) {
        $key = strtoupper($key);
        if($check)   $content .= 'defined(\'' . $key . '\') or ';
        if (is_int($val) || is_float($val)) {
            $content .= "define('" . $key . "'," . $val . ');';
        } elseif (is_bool($val)) {
            $val = ($val) ? 'true' : 'false';
            $content .= "define('" . $key . "'," . $val . ');';
        } elseif (is_string($val)) {
            $content .= "define('" . $key . "','" . addslashes($val) . "');";
        }
        $content    .= "\n";
    }
    return $content;
}
//[/RUNTIME]

/**
 * 添加和获取页面Trace记录
 * @param string $value 变量
 * @param string $label 标签
 * @param string $level 日志级别 
 * @param boolean $record 是否记录日志
 * @return void
 */
function trace($value='[think]',$label='',$level='DEBUG',$record=false) {
    static $_trace =  array();
    if('[think]' === $value){ // 获取trace信息
        return $_trace;
    }else{
        $info   =   ($label?$label.':':'').print_r($value,true);
        if('ERR' == $level && C('TRACE_EXCEPTION')) {// 抛出异常
            throw_exception($info);
        }
        $level  =   strtoupper($level);
        if(!isset($_trace[$level])) {
                $_trace[$level] =   array();
            }
        $_trace[$level][]   = $info;
        if((defined('IS_AJAX') && IS_AJAX) || !C('SHOW_PAGE_TRACE')  || $record) {
            Log::record($info,$level,$record);
        }
    }
}

 
function object_array($array) {
	if (is_object ( $array )) {
		$array = ( array ) $array;
	}
	if (is_array ( $array )) {
		foreach ( $array as $key => $value ) {
			$array [$key] = object_array ( $value );
		}
	}
	return $array;
}

/**
 * 生成简码
 */
function short($input) {
	$base32 = array (
			'a','b',
			'c','d',
			'e','f',
			'g','h',
			'i','j',
			'k','l',
			'm','n',
			'o','p',
			'q','r',
			's','t',
			'u','v',
			'w','x',
			'y','z',
			'0','1',
			'2','3',
			'4','5'
	);
	$hex = md5 ( $input );
	// echo "md5:".$hex.'<br>';
	$hexLen = strlen ( $hex );
	$subHexLen = $hexLen / 8;
	$output = array ();

	for($i = 0; $i < $subHexLen; $i ++) {
		$subHex = substr ( $hex, $i * 8, 8 );
		// echo $i."substr: ".$subHex.'<br>';
		$int = 0x3FFFFFFF & (1 * ('0x' . $subHex));
		// echo $i."0x3FFFFFFF: ".$int.'<br>';
		$out = '';

		for($j = 0; $j < 6; $j ++) {
			$val = 0x0000001F & $int;
			// echo $i.$j."0x0000001F: ".$val.'<br>';
			$out .= $base32 [$val];
				
			$int = $int >> 5;
		}

		$output [] = $out;
	}
	return $output ['0'];
}
/**
 *
 * @param 手机号码 $mb
 * @param 短信内容 $ct
 * @return string
 */
function sendMobiMsg($mbnum,$mbmsgct)	////$mb：手机号码; $ct：发信内容
{
	linuxSendMobiMsg($mbnum,$mbmsgct);
	/*$sinf=array("lkw","888888");
	 $smsObject = new COM ("PostMsg30.msg");
	//global $username,$password,$smsObject,$outmsg;
	$Proc = 0;
	$first = substr($$mbnum, 0, 2);
	if ($first < "13")
		$Proc = 1;
	$ret = $smsObject->Post($sinf[0],$sinf[1],$mbnum,$mbmsgct,$Proc,"");
	return $ret;*/
}

/**
 * LINUX 系统下专用
 * @param 手机号码 $mb
 * @param 短信内容 $ct
 * @return string
 */
function linuxSendMobiMsg($mbnum,$mbmsgct)	////$mb：手机号码; $ct：发信内容
{
	$sinf=array("lkw","888888");

	if(is_array($mbnum)) {
		$mbnum = join("+", $mbnum);
	}

	//$mbmsgct = mb_convert_encoding($mbmsgct,"GBK", "UTF-8");
	$ret = file_get_contents("http://211.147.224.154:13013/cgi-bin/sendsms?username=lkw&password=888888&to=$mbnum&text=$mbmsgct&subid=");

	if($ret == "-99"){
		//余额不足
		$ret = "-99";
	}elseif($ret == "0") {
		//发送成功
		$ret = "1";
	}else {
		//发送失败
		$ret = "0";
	}
	return $ret;
}
function myip2long($ip) {
	$ip_arr = split ( '\.', $ip );
	$iplong = (16777216 * intval ( $ip_arr [0] )) + (65536 * intval ( $ip_arr [1] )) + (256 * intval ( $ip_arr [2] )) + intval ( $ip_arr [3] );
	return $iplong;
}


function reimg($str, $conten = 1) {
	$str = str_replace ( './', '/', $str);
	if ($conten == 1) {
		$str = str_replace ( '"/Uploads/', '"http://img2013.smw01.com/Uploads/', $str );
		$str = str_replace ( '"/Public/', '"http://img2013.smw01.com/Public/', $str );
		$str = str_replace ( '"/91Uploads/', '"http://img0217.smw01.com/', $str );
	} else {
		if (strpos ( $str, 'http:' ) === FALSE) {
			$str = str_replace ( '/Uploads/', 'http://img2013.smw01.com/Uploads/', $str );
			$str = str_replace ( '/Public/', 'http://img2013.smw01.com/Public/', $str );
			$str = str_replace ( '/91Uploads/', 'http://img0217.smw01.com/', $str );
		}
	}
	return $str;
}

/**
 * 返回图片地址
 * @param string $_imageurl
 * @return string|NULL
 */
function addrimage($_imageurl){
	if($_imageurl){
// 		if (strpos ( $_imageurl, 'http:' ) === FALSE) {
			$_imageurl = str_replace ( './', '/', $_imageurl);
			$_imageurl = str_replace ( 'http://www.smw01.com/Uploads/', '/Uploads/', $_imageurl );
			$_imageurl = str_replace ( 'http://img2013.smw01.com/Uploads/', '/Uploads/', $_imageurl );
			$_imageurl = str_replace ( '/Uploads/', 'http://img2013.smw01.com/Uploads/', $_imageurl );
			//$_imageurl = 'http://www.smw01.com'.$_imageurl;
		
		//	$_imageurl = str_replace ( '"/Uploads/', '"http://www.smw01.com/Uploads/', $_imageurl );
			$_imageurl = str_replace ( '/Public/', 'http://img2013.smw01.com/Public/', $_imageurl );
// 			$_imageurl = str_replace ( 'http://newerp.smw01.com/91Uploads/', '/91Uploads/', $_imageurl );
	  	  $_imageurl = str_replace ( '/91Uploads/', 'http://img0217.smw01.com/', $_imageurl );

// 		}
		return $_imageurl;
	}else{
		return NULL;
	}
}


function myexplod($arr = array(), $split = '|') {
	$newarr = array ();
	foreach ( $arr as $r ) {
		if (stripos ( $r, '|' ) !== false) {
			$v = explode ( "|", $r );
			$newarr [$v ['1']] = $v ['0'];
		}
	}
	return $newarr;
}
function myencode($string) {
	$data = base64_encode ( $string );
	$data = str_replace ( array (
			'+',
			'/',
			'='
	), array (
			'-',
			'_',
			''
	), $data );
	return $data;
}
function mydecode($string) {
	$data = str_replace ( array (
			'-',
			'_'
	), array (
			'+',
			'/'
	), $string );
	$mod4 = strlen ( $data ) % 4;
	if ($mod4) {
		$data .= substr ( '====', $mod4 );
	}
	return base64_decode ( $data );
}

/**
 * 将日期格式转为时间戳
 *
 * @param $time 格式化的日期如
 *        	2012-09-03
 */
function gettime($time) {
	if (stripos ( $time, ' ' ) !== FALSE) {
		$temp = explode ( ' ', $time );
		$date = $temp ['0'];
		$time = $temp ['1'];
		if (stripos ( $date, '-' ) !== FALSE) {
			$date = explode ( '-', $date );
		}
		if (stripos ( $time, ':' ) !== FALSE) {
			$time = explode ( ':', $time );
		}
		$starttime = mktime ( $time ['0'], $time ['1'], $time ['2'], $date ['1'], $date ['2'], $date ['0'] );
	} else {
		if (stripos ( $time, '-' ) !== FALSE) {
			$temp = explode ( '-', $time );
			$starttime = mktime ( 0, 0, 0, $temp ['1'], $temp ['2'], $temp ['0'] );
		}
	}
	return $starttime;
}

/**
 * 取数组内的一个元素值为数组索引
 */
function field2key($arr, $field,$levle=1) {
	$newarr = array ();
	if (is_array ( $arr )) {
		foreach ( $arr as $v ) {
			if($levle==1){
				$newarr [$v [$field]] = $v;
			}else{
				$newarr [$v [$field]][] = $v;
			}
		}
	} else {
		$newarr = $arr;
	}
	return $newarr;
}

/**
 * 将字符格式化后转为数组对应键的值
 *
 * @param unknown_type $str
 * @param 对应数组 $arr
 * @param 对应数组值的键名 $val
 * @param 分割间隔符 $spl
 * @param 组合间隔符 $impl
 */
function str2array_value($str, $arr, $val, $spl = ',', $impl = '/') {
	if (stripos ( $str, $spl ) !== false) {
		$str = explode ( $spl, $str );
		$newarr = array ();
		if (count ( $str ) > 0) {
			foreach ( $str as $v ) {
				$newarr [] = $arr [$v] [$val];
			}
			$str = implode ( $impl, $newarr );
		}
	} else {
		$str = $arr [$str] [$val];
	}
	return $str;
}

/**
 * +----------------------------------------------------------
 * 字符串截取，支持中文和其他编码
 * +----------------------------------------------------------
 *
 * @static
 *
 * @access public
 *         +----------------------------------------------------------
 * @param string $str
 *        	需要转换的字符串
 * @param string $start
 *        	开始位置
 * @param string $length
 *        	截取长度
 * @param string $charset
 *        	编码格式
 * @param string $suffix
 *        	截断显示字符
 *        	+----------------------------------------------------------
 * @return string +----------------------------------------------------------
 */
function msubstr($str, $start = 0, $length, $charset = "utf-8", $suffix = true) {
	if (function_exists ( "mb_substr" ))
		$slice = mb_substr ( $str, $start, $length, $charset );
	elseif (function_exists ( 'iconv_substr' )) {
		$slice = iconv_substr ( $str, $start, $length, $charset );
		if (false === $slice) {
			$slice = '';
		}
	} else {
		$re ['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
		$re ['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
		$re ['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
		$re ['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
		preg_match_all ( $re [$charset], $str, $match );
		$slice = join ( "", array_slice ( $match [0], $start, $length ) );
	}
	return $suffix ? $slice . '...' : $slice;
}


/**
 * +----------------------------------------------------------
 * 产生随机字串，可用来自动生成密码 默认长度6位 字母和数字混合
 * +----------------------------------------------------------
 *
 * @param string $len
 *        	长度
 * @param string $type
 *        	字串类型
 *        	0 字母 1 数字 其它 混合
 * @param string $addChars
 *        	额外字符
 *        	+----------------------------------------------------------
 * @return string +----------------------------------------------------------
 */
function rand_string($len = 6, $type = '', $addChars = '') {
	$str = '';
	switch ($type) {
		case 0 :
			$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' . $addChars;
			break;
		case 1 :
			$chars = str_repeat ( '0123456789', 3 );
			break;
		case 2 :
			$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' . $addChars;
			break;
		case 3 :
			$chars = 'abcdefghijklmnopqrstuvwxyz' . $addChars;
			break;
		case 4 :
			$chars = "们以我到他会作时要动国产的一是工就年阶义发成部民可出能方进在了不和有大这主中人上为来分生对于学下级地个用同行面说种过命度革而多子后自社加小机也经力线本电高量长党得实家定深法表着水理化争现所二起政三好十战无农使性前等反体合斗路图把结第里正新开论之物从当两些还天资事队批点育重其思与间内去因件日利相由压员气业代全组数果期导平各基或月毛然如应形想制心样干都向变关问比展那它最及外没看治提五解系林者米群头意只明四道马认次文通但条较克又公孔领军流入接席位情运器并飞原油放立题质指建区验活众很教决特此常石强极土少已根共直团统式转别造切九你取西持总料连任志观调七么山程百报更见必真保热委手改管处己将修支识病象几先老光专什六型具示复安带每东增则完风回南广劳轮科北打积车计给节做务被整联步类集号列温装即毫知轴研单色坚据速防史拉世设达尔场织历花受求传口断况采精金界品判参层止边清至万确究书术状厂须离再目海交权且儿青才证低越际八试规斯近注办布门铁需走议县兵固除般引齿千胜细影济白格效置推空配刀叶率述今选养德话查差半敌始片施响收华觉备名红续均药标记难存测士身紧液派准斤角降维板许破述技消底床田势端感往神便贺村构照容非搞亚磨族火段算适讲按值美态黄易彪服早班麦削信排台声该击素张密害侯草何树肥继右属市严径螺检左页抗苏显苦英快称坏移约巴材省黑武培著河帝仅针怎植京助升王眼她抓含苗副杂普谈围食射源例致酸旧却充足短划剂宣环落首尺波承粉践府鱼随考刻靠够满夫失包住促枝局菌杆周护岩师举曲春元超负砂封换太模贫减阳扬江析亩木言球朝医校古呢稻宋听唯输滑站另卫字鼓刚写刘微略范供阿块某功套友限项余倒卷创律雨让骨远帮初皮播优占死毒圈伟季训控激找叫云互跟裂粮粒母练塞钢顶策双留误础吸阻故寸盾晚丝女散焊功株亲院冷彻弹错散商视艺灭版烈零室轻血倍缺厘泵察绝富城冲喷壤简否柱李望盘磁雄似困巩益洲脱投送奴侧润盖挥距触星松送获兴独官混纪依未突架宽冬章湿偏纹吃执阀矿寨责熟稳夺硬价努翻奇甲预职评读背协损棉侵灰虽矛厚罗泥辟告卵箱掌氧恩爱停曾溶营终纲孟钱待尽俄缩沙退陈讨奋械载胞幼哪剥迫旋征槽倒握担仍呀鲜吧卡粗介钻逐弱脚怕盐末阴丰雾冠丙街莱贝辐肠付吉渗瑞惊顿挤秒悬姆烂森糖圣凹陶词迟蚕亿矩康遵牧遭幅园腔订香肉弟屋敏恢忘编印蜂急拿扩伤飞露核缘游振操央伍域甚迅辉异序免纸夜乡久隶缸夹念兰映沟乙吗儒杀汽磷艰晶插埃燃欢铁补咱芽永瓦倾阵碳演威附牙芽永瓦斜灌欧献顺猪洋腐请透司危括脉宜笑若尾束壮暴企菜穗楚汉愈绿拖牛份染既秋遍锻玉夏疗尖殖井费州访吹荣铜沿替滚客召旱悟刺脑措贯藏敢令隙炉壳硫煤迎铸粘探临薄旬善福纵择礼愿伏残雷延烟句纯渐耕跑泽慢栽鲁赤繁境潮横掉锥希池败船假亮谓托伙哲怀割摆贡呈劲财仪沉炼麻罪祖息车穿货销齐鼠抽画饲龙库守筑房歌寒喜哥洗蚀废纳腹乎录镜妇恶脂庄擦险赞钟摇典柄辩竹谷卖乱虚桥奥伯赶垂途额壁网截野遗静谋弄挂课镇妄盛耐援扎虑键归符庆聚绕摩忙舞遇索顾胶羊湖钉仁音迹碎伸灯避泛亡答勇频皇柳哈揭甘诺概宪浓岛袭谁洪谢炮浇斑讯懂灵蛋闭孩释乳巨徒私银伊景坦累匀霉杜乐勒隔弯绩招绍胡呼痛峰零柴簧午跳居尚丁秦稍追梁折耗碱殊岗挖氏刃剧堆赫荷胸衡勤膜篇登驻案刊秧缓凸役剪川雪链渔啦脸户洛孢勃盟买杨宗焦赛旗滤硅炭股坐蒸凝竟陷枪黎救冒暗洞犯筒您宋弧爆谬涂味津臂障褐陆啊健尊豆拔莫抵桑坡缝警挑污冰柬嘴啥饭塑寄赵喊垫丹渡耳刨虎笔稀昆浪萨茶滴浅拥穴覆伦娘吨浸袖珠雌妈紫戏塔锤震岁貌洁剖牢锋疑霸闪埔猛诉刷狠忽灾闹乔唐漏闻沈熔氯荒茎男凡抢像浆旁玻亦忠唱蒙予纷捕锁尤乘乌智淡允叛畜俘摸锈扫毕璃宝芯爷鉴秘净蒋钙肩腾枯抛轨堂拌爸循诱祝励肯酒绳穷塘燥泡袋朗喂铝软渠颗惯贸粪综墙趋彼届墨碍启逆卸航衣孙龄岭骗休借" . $addChars;
			break;
		default :
			// 默认去掉了容易混淆的字符oOLl和数字01，要添加请使用addChars参数
			$chars = 'ABCDEFGHIJKMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789' . $addChars;
			break;
	}
	if ($len > 10) { // 位数过长重复字符串一定次数
		$chars = $type == 1 ? str_repeat ( $chars, $len ) : str_repeat ( $chars, 5 );
	}
	if ($type != 4) {
		$chars = str_shuffle ( $chars );
		$str = substr ( $chars, 0, $len );
	} else {
		// 中文随机字
		for($i = 0; $i < $len; $i ++) {
			$str .= msubstr ( $chars, floor ( mt_rand ( 0, mb_strlen ( $chars, 'utf-8' ) - 1 ) ), 1 );
		}
	}
	return $str;
}

/**
 * +----------------------------------------------------------
 * 获取登录验证码 默认为4位数字
 * +----------------------------------------------------------
 *
 * @param string $fmode
 *        	文件名
 *        	+----------------------------------------------------------
 * @return string +----------------------------------------------------------
 */
function build_verify($length = 4, $mode = 1) {
	return rand_string ( $length, $mode );
}

/**
 * +----------------------------------------------------------
 * 字节格式化 把字节数格式为 B K M G T 描述的大小
 * +----------------------------------------------------------
 *
 * @return string +----------------------------------------------------------
 */
function byte_format($size, $dec = 2) {
	$a = array (
			"B",
			"KB",
			"MB",
			"GB",
			"TB",
			"PB"
	);
	$pos = 0;
	while ( $size >= 1024 ) {
		$size /= 1024;
		$pos ++;
	}
	return round ( $size, $dec ) . " " . $a [$pos];
}

/**
 * +----------------------------------------------------------
 * 检查字符串是否是UTF8编码
 * +----------------------------------------------------------
 *
 * @param string $string
 *        	字符串
 *        	+----------------------------------------------------------
 * @return Boolean +----------------------------------------------------------
 */
function is_utf8($string) {
	return preg_match ( '%^(?:
         [\x09\x0A\x0D\x20-\x7E]            # ASCII
       | [\xC2-\xDF][\x80-\xBF]             # non-overlong 2-byte
       |  \xE0[\xA0-\xBF][\x80-\xBF]        # excluding overlongs
       | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}  # straight 3-byte
       |  \xED[\x80-\x9F][\x80-\xBF]        # excluding surrogates
       |  \xF0[\x90-\xBF][\x80-\xBF]{2}     # planes 1-3
       | [\xF1-\xF3][\x80-\xBF]{3}          # planes 4-15
       |  \xF4[\x80-\x8F][\x80-\xBF]{2}     # plane 16
    )*$%xs', $string );
}
/**
 * +----------------------------------------------------------
 * 代码加亮
 * +----------------------------------------------------------
 *
 * @param String $str
 *        	要高亮显示的字符串 或者 文件名
 * @param Boolean $show
 *        	是否输出
 *        	+----------------------------------------------------------
 * @return String +----------------------------------------------------------
 */
function highlight_code($str, $show = false) {
	if (file_exists ( $str )) {
		$str = file_get_contents ( $str );
	}
	$str = stripslashes ( trim ( $str ) );
	// The highlight string function encodes and highlights
	// brackets so we need them to start raw
	$str = str_replace ( array (
			'&lt;',
			'&gt;'
	), array (
			'<',
			'>'
	), $str );

	// Replace any existing PHP tags to temporary markers so they don't
	// accidentally
	// break the string out of PHP, and thus, thwart the highlighting.

	$str = str_replace ( array (
			'&lt;?php',
			'?&gt;',
			'\\'
	), array (
			'phptagopen',
			'phptagclose',
			'backslashtmp'
	), $str );

	// The highlight_string function requires that the text be surrounded
	// by PHP tags. Since we don't know if A) the submitted text has PHP tags,
	// or B) whether the PHP tags enclose the entire string, we will add our
	// own PHP tags around the string along with some markers to make
	// replacement easier later

	$str = '<?php //tempstart' . "\n" . $str . '//tempend ?>'; // <?// <?

	// All the magic happens here, baby!
	$str = highlight_string ( $str, TRUE );

	// Prior to PHP 5, the highlight function used icky font tags
	// so we'll replace them with span tags.
	if (abs ( phpversion () ) < 5) {
		$str = str_replace ( array (
				'<font ',
				'</font>'
		), array (
				'<span ',
				'</span>'
		), $str );
		$str = preg_replace ( '#color="(.*?)"#', 'style="color: \\1"', $str );
	}

	// Remove our artificially added PHP
	$str = preg_replace ( "#\<code\>.+?//tempstart\<br />\</span\>#is", "<code>\n", $str );
	$str = preg_replace ( "#\<code\>.+?//tempstart\<br />#is", "<code>\n", $str );
	$str = preg_replace ( "#//tempend.+#is", "</span>\n</code>", $str );

	// Replace our markers back to PHP tags.
	$str = str_replace ( array (
			'phptagopen',
			'phptagclose',
			'backslashtmp'
	), array (
			'&lt;?php',
			'?&gt;',
			'\\'
	), $str ); //<?// <?
	$line = explode ( "<br />", rtrim ( ltrim ( $str, '<code>' ), '</code>' ) );
	$result = '<div class="code"><ol>';
	foreach ( $line as $key => $val ) {
		$result .= '<li>' . $val . '</li>';
	}
	$result .= '</ol></div>';
	$result = str_replace ( "\n", "", $result );
	if ($show !== false) {
		echo ($result);
	} else {
		return $result;
	}
}

// 输出安全的html
function h($text, $tags = null) {
	$text = trim ( $text );
	// 完全过滤注释
	$text = preg_replace ( '/<!--?.*-->/', '', $text );
	// 完全过滤动态代码
	$text = preg_replace ( '/<\?|\?' . '>/', '', $text );
	// 完全过滤js
	$text = preg_replace ( '/<script?.*\/script>/', '', $text );

	$text = str_replace ( '[', '&#091;', $text );
	$text = str_replace ( ']', '&#093;', $text );
	$text = str_replace ( '|', '&#124;', $text );
	// 过滤换行符
	$text = preg_replace ( '/\r?\n/', '', $text );
	// br
	$text = preg_replace ( '/<br(\s\/)?' . '>/i', '[br]', $text );
	$text = preg_replace ( '/(\[br\]\s*){10,}/i', '[br]', $text );
	// 过滤危险的属性，如：过滤on事件lang js
	while ( preg_match ( '/(<[^><]+)( lang|on|action|background|codebase|dynsrc|lowsrc)[^><]+/i', $text, $mat ) ) {
		$text = str_replace ( $mat [0], $mat [1], $text );
	}
	while ( preg_match ( '/(<[^><]+)(window\.|javascript:|js:|about:|file:|document\.|vbs:|cookie)([^><]*)/i', $text, $mat ) ) {
		$text = str_replace ( $mat [0], $mat [1] . $mat [3], $text );
	}
	if (empty ( $tags )) {
		$tags = 'table|td|th|tr|i|b|u|strong|img|p|br|div|strong|em|ul|ol|li|dl|dd|dt|a';
	}
	// 允许的HTML标签
	$text = preg_replace ( '/<(' . $tags . ')( [^><\[\]]*)>/i', '[\1\2]', $text );
	// 过滤多余html
	$text = preg_replace ( '/<\/?(html|head|meta|link|base|basefont|body|bgsound|title|style|script|form|iframe|frame|frameset|applet|id|ilayer|layer|name|script|style|xml)[^><]*>/i', '', $text );
	// 过滤合法的html标签
	while ( preg_match ( '/<([a-z]+)[^><\[\]]*>[^><]*<\/\1>/i', $text, $mat ) ) {
		$text = str_replace ( $mat [0], str_replace ( '>', ']', str_replace ( '<', '[', $mat [0] ) ), $text );
	}
	// 转换引号
	while ( preg_match ( '/(\[[^\[\]]*=\s*)(\"|\')([^\2=\[\]]+)\2([^\[\]]*\])/i', $text, $mat ) ) {
		$text = str_replace ( $mat [0], $mat [1] . '|' . $mat [3] . '|' . $mat [4], $text );
	}
	// 过滤错误的单个引号
	while ( preg_match ( '/\[[^\[\]]*(\"|\')[^\[\]]*\]/i', $text, $mat ) ) {
		$text = str_replace ( $mat [0], str_replace ( $mat [1], '', $mat [0] ), $text );
	}
	// 转换其它所有不合法的 < >
	$text = str_replace ( '<', '&lt;', $text );
	$text = str_replace ( '>', '&gt;', $text );
	$text = str_replace ( '"', '&quot;', $text );
	// 反转换
	$text = str_replace ( '[', '<', $text );
	$text = str_replace ( ']', '>', $text );
	$text = str_replace ( '|', '"', $text );
	// 过滤多余空格
	$text = str_replace ( '  ', ' ', $text );
	return $text;
}
function ubb($Text) {
	$Text = trim ( $Text );
	// $Text=htmlspecialchars($Text);
	$Text = preg_replace ( "/\\t/is", "  ", $Text );
	$Text = preg_replace ( "/\[h1\](.+?)\[\/h1\]/is", "<h1>\\1</h1>", $Text );
	$Text = preg_replace ( "/\[h2\](.+?)\[\/h2\]/is", "<h2>\\1</h2>", $Text );
	$Text = preg_replace ( "/\[h3\](.+?)\[\/h3\]/is", "<h3>\\1</h3>", $Text );
	$Text = preg_replace ( "/\[h4\](.+?)\[\/h4\]/is", "<h4>\\1</h4>", $Text );
	$Text = preg_replace ( "/\[h5\](.+?)\[\/h5\]/is", "<h5>\\1</h5>", $Text );
	$Text = preg_replace ( "/\[h6\](.+?)\[\/h6\]/is", "<h6>\\1</h6>", $Text );
	$Text = preg_replace ( "/\[separator\]/is", "", $Text );
	$Text = preg_replace ( "/\[center\](.+?)\[\/center\]/is", "<center>\\1</center>", $Text );
	$Text = preg_replace ( "/\[url=http:\/\/([^\[]*)\](.+?)\[\/url\]/is", "<a href=\"http://\\1\" target=_blank>\\2</a>", $Text );
	$Text = preg_replace ( "/\[url=([^\[]*)\](.+?)\[\/url\]/is", "<a href=\"http://\\1\" target=_blank>\\2</a>", $Text );
	$Text = preg_replace ( "/\[url\]http:\/\/([^\[]*)\[\/url\]/is", "<a href=\"http://\\1\" target=_blank>\\1</a>", $Text );
	$Text = preg_replace ( "/\[url\]([^\[]*)\[\/url\]/is", "<a href=\"\\1\" target=_blank>\\1</a>", $Text );
	$Text = preg_replace ( "/\[img\](.+?)\[\/img\]/is", "<img src=\\1>", $Text );
	$Text = preg_replace ( "/\[color=(.+?)\](.+?)\[\/color\]/is", "<font color=\\1>\\2</font>", $Text );
	$Text = preg_replace ( "/\[size=(.+?)\](.+?)\[\/size\]/is", "<font size=\\1>\\2</font>", $Text );
	$Text = preg_replace ( "/\[sup\](.+?)\[\/sup\]/is", "<sup>\\1</sup>", $Text );
	$Text = preg_replace ( "/\[sub\](.+?)\[\/sub\]/is", "<sub>\\1</sub>", $Text );
	$Text = preg_replace ( "/\[pre\](.+?)\[\/pre\]/is", "<pre>\\1</pre>", $Text );
	$Text = preg_replace ( "/\[email\](.+?)\[\/email\]/is", "<a href='mailto:\\1'>\\1</a>", $Text );
	$Text = preg_replace ( "/\[colorTxt\](.+?)\[\/colorTxt\]/eis", "color_txt('\\1')", $Text );
	$Text = preg_replace ( "/\[emot\](.+?)\[\/emot\]/eis", "emot('\\1')", $Text );
	$Text = preg_replace ( "/\[i\](.+?)\[\/i\]/is", "<i>\\1</i>", $Text );
	$Text = preg_replace ( "/\[u\](.+?)\[\/u\]/is", "<u>\\1</u>", $Text );
	$Text = preg_replace ( "/\[b\](.+?)\[\/b\]/is", "<b>\\1</b>", $Text );
	$Text = preg_replace ( "/\[quote\](.+?)\[\/quote\]/is", " <div class='quote'><h5>引用:</h5><blockquote>\\1</blockquote></div>", $Text );
	$Text = preg_replace ( "/\[code\](.+?)\[\/code\]/eis", "highlight_code('\\1')", $Text );
	$Text = preg_replace ( "/\[php\](.+?)\[\/php\]/eis", "highlight_code('\\1')", $Text );
	$Text = preg_replace ( "/\[sig\](.+?)\[\/sig\]/is", "<div class='sign'>\\1</div>", $Text );
	$Text = preg_replace ( "/\\n/is", "<br/>", $Text );
	return $Text;
}

// 随机生成一组字符串
function build_count_rand($number, $length = 4, $mode = 1) {
	if ($mode == 1 && $length < strlen ( $number )) {
		// 不足以生成一定数量的不重复数字
		return false;
	}
	$rand = array ();
	for($i = 0; $i < $number; $i ++) {
		$rand [] = rand_string ( $length, $mode );
	}
	$unqiue = array_unique ( $rand );
	if (count ( $unqiue ) == count ( $rand )) {
		return $rand;
	}
	$count = count ( $rand ) - count ( $unqiue );
	for($i = 0; $i < $count * 3; $i ++) {
		$rand [] = rand_string ( $length, $mode );
	}
	$rand = array_slice ( array_unique ( $rand ), 0, $number );
	return $rand;
}
function remove_xss($val) {
	// remove all non-printable characters. CR(0a) and LF(0b) and TAB(9) are
	// allowed
	// this prevents some character re-spacing such as <java\0script>
	// note that you have to handle splits with \n, \r, and \t later since they
	// *are* allowed in some inputs
	$val = preg_replace ( '/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/', '', $val );

	// straight replacements, the user should never need these since they're
	// normal characters
	// this prevents like <IMG SRC=@avascript:alert('XSS')>
	$search = 'abcdefghijklmnopqrstuvwxyz';
	$search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
	$search .= '1234567890!@#$%^&*()';
	$search .= '~`";:?+/={}[]-_|\'\\';
	for($i = 0; $i < strlen ( $search ); $i ++) {
		// ;? matches the ;, which is optional
		// 0{0,7} matches any padded zeros, which are optional and go up to 8
		// chars

		// @ @ search for the hex values
		$val = preg_replace ( '/(&#[xX]0{0,8}' . dechex ( ord ( $search [$i] ) ) . ';?)/i', $search [$i], $val ); // with
		// a
		// ;
		// @
		// @
		// 0{0,7}
		// matches
		// '0'
		// zero
		// to
		// seven
		// times
		$val = preg_replace ( '/(&#0{0,8}' . ord ( $search [$i] ) . ';?)/', $search [$i], $val ); // with
		// a
		// ;
	}

	// now the only remaining whitespace attacks are \t, \n, and \r
	$ra1 = array (
			'javascript',
			'vbscript',
			'expression',
			'applet',
			'meta',
			'xml',
			'blink',
			'link',
			'style',
			'script',
			'embed',
			'object',
			'iframe',
			'frame',
			'frameset',
			'ilayer',
			'layer',
			'bgsound',
			'title',
			'base'
	);
	$ra2 = array (
			'onabort',
			'onactivate',
			'onafterprint',
			'onafterupdate',
			'onbeforeactivate',
			'onbeforecopy',
			'onbeforecut',
			'onbeforedeactivate',
			'onbeforeeditfocus',
			'onbeforepaste',
			'onbeforeprint',
			'onbeforeunload',
			'onbeforeupdate',
			'onblur',
			'onbounce',
			'oncellchange',
			'onchange',
			'onclick',
			'oncontextmenu',
			'oncontrolselect',
			'oncopy',
			'oncut',
			'ondataavailable',
			'ondatasetchanged',
			'ondatasetcomplete',
			'ondblclick',
			'ondeactivate',
			'ondrag',
			'ondragend',
			'ondragenter',
			'ondragleave',
			'ondragover',
			'ondragstart',
			'ondrop',
			'onerror',
			'onerrorupdate',
			'onfilterchange',
			'onfinish',
			'onfocus',
			'onfocusin',
			'onfocusout',
			'onhelp',
			'onkeydown',
			'onkeypress',
			'onkeyup',
			'onlayoutcomplete',
			'onload',
			'onlosecapture',
			'onmousedown',
			'onmouseenter',
			'onmouseleave',
			'onmousemove',
			'onmouseout',
			'onmouseover',
			'onmouseup',
			'onmousewheel',
			'onmove',
			'onmoveend',
			'onmovestart',
			'onpaste',
			'onpropertychange',
			'onreadystatechange',
			'onreset',
			'onresize',
			'onresizeend',
			'onresizestart',
			'onrowenter',
			'onrowexit',
			'onrowsdelete',
			'onrowsinserted',
			'onscroll',
			'onselect',
			'onselectionchange',
			'onselectstart',
			'onstart',
			'onstop',
			'onsubmit',
			'onunload'
	);
	$ra = array_merge ( $ra1, $ra2 );

	$found = true; // keep replacing as long as the previous round replaced
	// something
	while ( $found == true ) {
		$val_before = $val;
		for($i = 0; $i < sizeof ( $ra ); $i ++) {
			$pattern = '/';
			for($j = 0; $j < strlen ( $ra [$i] ); $j ++) {
				if ($j > 0) {
					$pattern .= '(';
					$pattern .= '(&#[xX]0{0,8}([9ab]);)';
					$pattern .= '|';
					$pattern .= '|(&#0{0,8}([9|10|13]);)';
					$pattern .= ')*';
				}
				$pattern .= $ra [$i] [$j];
			}
			$pattern .= '/i';
			$replacement = substr ( $ra [$i], 0, 2 ) . '<x>' . substr ( $ra [$i], 2 ); // add
			// in <> to
			// nerf the
			// tag
			$val = preg_replace ( $pattern, $replacement, $val ); // filter out the
			// hex tags
			if ($val_before == $val) {
				// no replacements were made, so exit the loop
				$found = false;
			}
		}
	}
	return $val;
}

/**
 * +----------------------------------------------------------
 * 把返回的数据集转换成Tree
 * +----------------------------------------------------------
 *
 * @access public
 *         +----------------------------------------------------------
 * @param array $list
 *        	要转换的数据集
 * @param string $pid
 *        	parent标记字段
 * @param string $level
 *        	level标记字段
 *        	+----------------------------------------------------------
 * @return array +----------------------------------------------------------

 */
function list_to_tree($list, $pk = 'id', $pid = 'pid', $child = '_child', $root = 0) {
	// 创建Tree
	$tree = array ();
	if (is_array ( $list )) {
		// 创建基于主键的数组引用
		$refer = array ();
		foreach ( $list as $key => $data ) {
			$refer [$data [$pk]] = & $list [$key];
		}
		foreach ( $list as $key => $data ) {
			// 判断是否存在parent
			$parentId = $data [$pid];
			if ($root == $parentId) {
				$tree [] = & $list [$key];
			} else {
				if (isset ( $refer [$parentId] )) {
					$parent = & $refer [$parentId];
					$parent [$child] [] = & $list [$key];
				}
			}
		}
	}
	return $tree;
}

/**
 * +----------------------------------------------------------
 * 对查询结果集进行排序
 * +----------------------------------------------------------
 *
 * @access public
 *         +----------------------------------------------------------
 * @param array $list
 *        	查询结果
 * @param string $field
 *        	排序的字段名
 * @param array $sortby
 *        	排序类型
 *        	asc正向排序 desc逆向排序 nat自然排序
 *        	+----------------------------------------------------------
 * @return array +----------------------------------------------------------
 */
function list_sort_by($list, $field, $sortby = 'asc') {
	if (is_array ( $list )) {
		$refer = $resultSet = array ();
		foreach ( $list as $i => $data )
			$refer [$i] = &$data [$field];
		switch ($sortby) {
			case 'asc' : // 正向排序
				asort ( $refer );
				break;
			case 'desc' : // 逆向排序
				arsort ( $refer );
				break;
			case 'nat' : // 自然排序
				natcasesort ( $refer );
				break;
		}
		foreach ( $refer as $key => $val )
			$resultSet [] = &$list [$key];
		return $resultSet;
	}
	return false;
}

/**
 * +----------------------------------------------------------
 * 在数据列表中搜索
 * +----------------------------------------------------------
 *
 * @access public
 *         +----------------------------------------------------------
 * @param array $list
 *        	数据列表
 * @param mixed $condition
 *        	查询条件
 *        	支持 array('name'=>$value) 或者 name=$value
 *        	+----------------------------------------------------------
 * @return array +----------------------------------------------------------
 */
function list_search($list, $condition) {
	if (is_string ( $condition ))
		parse_str ( $condition, $condition );
	// 返回的结果集合
	$resultSet = array ();
	foreach ( $list as $key => $data ) {
		$find = false;
		foreach ( $condition as $field => $value ) {
			if (isset ( $data [$field] )) {
				if (0 === strpos ( $value, '/' )) {
					$find = preg_match ( $value, $data [$field] );
				} elseif ($data [$field] == $value) {
					$find = true;
				}
			}
		}
		if ($find)
			$resultSet [] = &$list [$key];
	}
	return $resultSet;
}

// 自动转换字符集 支持数组转换
function auto_charset($fContents, $from = 'gbk', $to = 'utf-8') {
	$from = strtoupper ( $from ) == 'UTF8' ? 'utf-8' : $from;
	$to = strtoupper ( $to ) == 'UTF8' ? 'utf-8' : $to;
	if (strtoupper ( $from ) === strtoupper ( $to ) || empty ( $fContents ) || (is_scalar ( $fContents ) && ! is_string ( $fContents ))) {
		// 如果编码相同或者非字符串标量则不转换
		return $fContents;
	}
	if (is_string ( $fContents )) {
		if (function_exists ( 'mb_convert_encoding' )) {
			return mb_convert_encoding ( $fContents, $to, $from );
		} elseif (function_exists ( 'iconv' )) {
			return iconv ( $from, $to, $fContents );
		} else {
			return $fContents;
		}
	} elseif (is_array ( $fContents )) {
		foreach ( $fContents as $key => $val ) {
			$_key = auto_charset ( $key, $from, $to );
			$fContents [$_key] = auto_charset ( $val, $from, $to );
			if ($key != $_key)
				unset ( $fContents [$key] );
		}
		return $fContents;
	} else {
		return $fContents;
	}
}
function sysmd5($str, $key = '', $type = 'sha1') {
	$key = $key ? $key : C ( 'ADMIN_ACCESS' );
	return hash ( $type, $str . $key );
}
/**
 *
 * @param string $string
 *        	原文或者密文
 * @param string $operation
 *        	操作(ENCODE | DECODE), 默认为 DECODE
 * @param string $key
 *        	密钥
 * @param int $expiry
 *        	密文有效期, 加密时候有效， 单位 秒，0 为永久有效
 * @return string 处理后的 原文或者 经过 base64_encode 处理后的密文
 *
 * @example $a = authcode('abc', 'ENCODE', 'key');
 *          $b = authcode($a, 'DECODE', 'key'); // $b(abc)
 *
 *          $a = authcode('abc', 'ENCODE', 'key', 3600);
 *          $b = authcode('abc', 'DECODE', 'key'); // 在一个小时内，$b(abc)，否则 $b 为空
 *
 */
function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {
	$ckey_length = 4;
	// 随机密钥长度 取值 0-32;
	// 加入随机密钥，可以令密文无任何规律，即便是原文和密钥完全相同，加密结果也会每次不同，增大破解难度。
	// 取值越大，密文变动规律越大，密文变化 = 16 的 $ckey_length 次方
	// 当此值为 0 时，则不产生随机密钥

	$keya = md5 ( substr ( $key, 0, 16 ) );
	$keyb = md5 ( substr ( $key, 16, 16 ) );
	$keyc = $ckey_length ? ($operation == 'DECODE' ? substr ( $string, 0, $ckey_length ) : substr ( md5 ( microtime () ), - $ckey_length )) : '';

	$cryptkey = $keya . md5 ( $keya . $keyc );
	$key_length = strlen ( $cryptkey );

	$string = $operation == 'DECODE' ? base64_decode ( substr ( $string, $ckey_length ) ) : sprintf ( '%010d', $expiry ? $expiry + time () : 0 ) . substr ( md5 ( $string . $keyb ), 0, 16 ) . $string;
	$string_length = strlen ( $string );

	$result = '';
	$box = range ( 0, 255 );

	$rndkey = array ();
	for($i = 0; $i <= 255; $i ++) {
		$rndkey [$i] = ord ( $cryptkey [$i % $key_length] );
	}

	for($j = $i = 0; $i < 256; $i ++) {
		$j = ($j + $box [$i] + $rndkey [$i]) % 256;
		$tmp = $box [$i];
		$box [$i] = $box [$j];
		$box [$j] = $tmp;
	}

	for($a = $j = $i = 0; $i < $string_length; $i ++) {
		$a = ($a + 1) % 256;
		$j = ($j + $box [$a]) % 256;
		$tmp = $box [$a];
		$box [$a] = $box [$j];
		$box [$j] = $tmp;
		$result .= chr ( ord ( $string [$i] ) ^ ($box [($box [$a] + $box [$j]) % 256]) );
	}

	if ($operation == 'DECODE') {
		if ((substr ( $result, 0, 10 ) == 0 || substr ( $result, 0, 10 ) - time () > 0) && substr ( $result, 10, 16 ) == substr ( md5 ( substr ( $result, 26 ) . $keyb ), 0, 16 )) {
			return substr ( $result, 26 );
		} else {
			return '';
		}
	} else {
		return $keyc . str_replace ( '=', '', base64_encode ( $result ) );
	}
}
function parseInt($string, $radix = '0') {
	if (is_array ( $string )) {
		foreach ( $string as $key => $val ) {
			$res [$key] = parseInt ( $val, $radix );
		}
	} else {
		$res = intval ( $string, $radix );
	}
	return ( int ) ($res);
}

function Pinyin($_String, $_Code = 'gb2312') {
	$_DataKey = "a|ai|an|ang|ao|ba|bai|ban|bang|bao|bei|ben|beng|bi|bian|biao|bie|bin|bing|bo|bu|ca|cai|can|cang|cao|ce|ceng|cha" . "|chai|chan|chang|chao|che|chen|cheng|chi|chong|chou|chu|chuai|chuan|chuang|chui|chun|chuo|ci|cong|cou|cu|" . "cuan|cui|cun|cuo|da|dai|dan|dang|dao|de|deng|di|dian|diao|die|ding|diu|dong|dou|du|duan|dui|dun|duo|e|en|er" . "|fa|fan|fang|fei|fen|feng|fo|fou|fu|ga|gai|gan|gang|gao|ge|gei|gen|geng|gong|gou|gu|gua|guai|guan|guang|gui" . "|gun|guo|ha|hai|han|hang|hao|he|hei|hen|heng|hong|hou|hu|hua|huai|huan|huang|hui|hun|huo|ji|jia|jian|jiang" . "|jiao|jie|jin|jing|jiong|jiu|ju|juan|jue|jun|ka|kai|kan|kang|kao|ke|ken|keng|kong|kou|ku|kua|kuai|kuan|kuang" . "|kui|kun|kuo|la|lai|lan|lang|lao|le|lei|leng|li|lia|lian|liang|liao|lie|lin|ling|liu|long|lou|lu|lv|luan|lue" . "|lun|luo|ma|mai|man|mang|mao|me|mei|men|meng|mi|mian|miao|mie|min|ming|miu|mo|mou|mu|na|nai|nan|nang|nao|ne" . "|nei|nen|neng|ni|nian|niang|niao|nie|nin|ning|niu|nong|nu|nv|nuan|nue|nuo|o|ou|pa|pai|pan|pang|pao|pei|pen" . "|peng|pi|pian|piao|pie|pin|ping|po|pu|qi|qia|qian|qiang|qiao|qie|qin|qing|qiong|qiu|qu|quan|que|qun|ran|rang" . "|rao|re|ren|reng|ri|rong|rou|ru|ruan|rui|run|ruo|sa|sai|san|sang|sao|se|sen|seng|sha|shai|shan|shang|shao|" . "she|shen|sheng|shi|shou|shu|shua|shuai|shuan|shuang|shui|shun|shuo|si|song|sou|su|suan|sui|sun|suo|ta|tai|" . "tan|tang|tao|te|teng|ti|tian|tiao|tie|ting|tong|tou|tu|tuan|tui|tun|tuo|wa|wai|wan|wang|wei|wen|weng|wo|wu" . "|xi|xia|xian|xiang|xiao|xie|xin|xing|xiong|xiu|xu|xuan|xue|xun|ya|yan|yang|yao|ye|yi|yin|ying|yo|yong|you" . "|yu|yuan|yue|yun|za|zai|zan|zang|zao|ze|zei|zen|zeng|zha|zhai|zhan|zhang|zhao|zhe|zhen|zheng|zhi|zhong|" . "zhou|zhu|zhua|zhuai|zhuan|zhuang|zhui|zhun|zhuo|zi|zong|zou|zu|zuan|zui|zun|zuo";
	$_DataValue = "-20319|-20317|-20304|-20295|-20292|-20283|-20265|-20257|-20242|-20230|-20051|-20036|-20032|-20026|-20002|-19990" . "|-19986|-19982|-19976|-19805|-19784|-19775|-19774|-19763|-19756|-19751|-19746|-19741|-19739|-19728|-19725" . "|-19715|-19540|-19531|-19525|-19515|-19500|-19484|-19479|-19467|-19289|-19288|-19281|-19275|-19270|-19263" . "|-19261|-19249|-19243|-19242|-19238|-19235|-19227|-19224|-19218|-19212|-19038|-19023|-19018|-19006|-19003" . "|-18996|-18977|-18961|-18952|-18783|-18774|-18773|-18763|-18756|-18741|-18735|-18731|-18722|-18710|-18697" . "|-18696|-18526|-18518|-18501|-18490|-18478|-18463|-18448|-18447|-18446|-18239|-18237|-18231|-18220|-18211" . "|-18201|-18184|-18183|-18181|-18012|-17997|-17988|-17970|-17964|-17961|-17950|-17947|-17931|-17928|-17922" . "|-17759|-17752|-17733|-17730|-17721|-17703|-17701|-17697|-17692|-17683|-17676|-17496|-17487|-17482|-17468" . "|-17454|-17433|-17427|-17417|-17202|-17185|-16983|-16970|-16942|-16915|-16733|-16708|-16706|-16689|-16664" . "|-16657|-16647|-16474|-16470|-16465|-16459|-16452|-16448|-16433|-16429|-16427|-16423|-16419|-16412|-16407" . "|-16403|-16401|-16393|-16220|-16216|-16212|-16205|-16202|-16187|-16180|-16171|-16169|-16158|-16155|-15959" . "|-15958|-15944|-15933|-15920|-15915|-15903|-15889|-15878|-15707|-15701|-15681|-15667|-15661|-15659|-15652" . "|-15640|-15631|-15625|-15454|-15448|-15436|-15435|-15419|-15416|-15408|-15394|-15385|-15377|-15375|-15369" . "|-15363|-15362|-15183|-15180|-15165|-15158|-15153|-15150|-15149|-15144|-15143|-15141|-15140|-15139|-15128" . "|-15121|-15119|-15117|-15110|-15109|-14941|-14937|-14933|-14930|-14929|-14928|-14926|-14922|-14921|-14914" . "|-14908|-14902|-14894|-14889|-14882|-14873|-14871|-14857|-14678|-14674|-14670|-14668|-14663|-14654|-14645" . "|-14630|-14594|-14429|-14407|-14399|-14384|-14379|-14368|-14355|-14353|-14345|-14170|-14159|-14151|-14149" . "|-14145|-14140|-14137|-14135|-14125|-14123|-14122|-14112|-14109|-14099|-14097|-14094|-14092|-14090|-14087" . "|-14083|-13917|-13914|-13910|-13907|-13906|-13905|-13896|-13894|-13878|-13870|-13859|-13847|-13831|-13658" . "|-13611|-13601|-13406|-13404|-13400|-13398|-13395|-13391|-13387|-13383|-13367|-13359|-13356|-13343|-13340" . "|-13329|-13326|-13318|-13147|-13138|-13120|-13107|-13096|-13095|-13091|-13076|-13068|-13063|-13060|-12888" . "|-12875|-12871|-12860|-12858|-12852|-12849|-12838|-12831|-12829|-12812|-12802|-12607|-12597|-12594|-12585" . "|-12556|-12359|-12346|-12320|-12300|-12120|-12099|-12089|-12074|-12067|-12058|-12039|-11867|-11861|-11847" . "|-11831|-11798|-11781|-11604|-11589|-11536|-11358|-11340|-11339|-11324|-11303|-11097|-11077|-11067|-11055" . "|-11052|-11045|-11041|-11038|-11024|-11020|-11019|-11018|-11014|-10838|-10832|-10815|-10800|-10790|-10780" . "|-10764|-10587|-10544|-10533|-10519|-10331|-10329|-10328|-10322|-10315|-10309|-10307|-10296|-10281|-10274" . "|-10270|-10262|-10260|-10256|-10254";
	$_TDataKey = explode ( '|', $_DataKey );
	$_TDataValue = explode ( '|', $_DataValue );
	$_Data = (PHP_VERSION >= '5.0') ? array_combine ( $_TDataKey, $_TDataValue ) : _Array_Combine ( $_TDataKey, $_TDataValue );
	arsort ( $_Data );
	reset ( $_Data );
	if ($_Code != 'gb2312')
		$_String = _U2_Utf8_Gb ( $_String );
	$_Res = '';
	for($i = 0; $i < strlen ( $_String ); $i ++) {
		$_P = ord ( substr ( $_String, $i, 1 ) );
		if ($_P > 160) {
			$_Q = ord ( substr ( $_String, ++ $i, 1 ) );
			$_P = $_P * 256 + $_Q - 65536;
		}
		$_Res .= _Pinyin ( $_P, $_Data );
	}
	return preg_replace ( "/[^a-z0-9]*/", '', $_Res );
}
function _Pinyin($_Num, $_Data) {
	if ($_Num > 0 && $_Num < 160)
		return chr ( $_Num );
	elseif ($_Num < - 20319 || $_Num > - 10247)
	return '';
	else {
		foreach ( $_Data as $k => $v ) {
			if ($v <= $_Num)
				break;
		}
		return $k;
	}
}
function _U2_Utf8_Gb($_C) {
	$_String = '';
	if ($_C < 0x80)
		$_String .= $_C;
	elseif ($_C < 0x800) {
		$_String .= chr ( 0xC0 | $_C >> 6 );
		$_String .= chr ( 0x80 | $_C & 0x3F );
	} elseif ($_C < 0x10000) {
		$_String .= chr ( 0xE0 | $_C >> 12 );
		$_String .= chr ( 0x80 | $_C >> 6 & 0x3F );
		$_String .= chr ( 0x80 | $_C & 0x3F );
	} elseif ($_C < 0x200000) {
		$_String .= chr ( 0xF0 | $_C >> 18 );
		$_String .= chr ( 0x80 | $_C >> 12 & 0x3F );
		$_String .= chr ( 0x80 | $_C >> 6 & 0x3F );
		$_String .= chr ( 0x80 | $_C & 0x3F );
	}
	return iconv ( 'UTF-8', 'GB2312//IGNORE', $_String );
}
function _Array_Combine($_Arr1, $_Arr2) {
	for($i = 0; $i < count ( $_Arr1 ); $i ++)
		$_Res [$_Arr1 [$i]] = $_Arr2 [$i];
	return $_Res;
}

function daxie($str){
	return substr(ucfirst($str),0,1);
}

/**
 * URL组装 支持不同URL模式
 * @param string $url URL表达式，格式：'[分组/模块/操作#锚点@域名]?参数1=值1&参数2=值2...'
 * @param string|array $vars 传入的参数，支持数组和字符串
 * @param string $suffix 伪静态后缀，默认为true表示获取配置值
 * @param boolean $redirect 是否跳转，如果设置为true则表示跳转到该URL地址
 * @param boolean $domain 是否显示域名
 * @return string
 */
function URL($url='',$vars='',$app='',$suffix=true,$redirect=false,$domain=false) {
	// 解析URL
	$info   =  parse_url($url);
	$url    =  !empty($info['path'])?$info['path']:ACTION_NAME;
	if(isset($info['fragment'])) { // 解析锚点
		$anchor =   $info['fragment'];
		if(false !== strpos($anchor,'?')) { // 解析参数
			list($anchor,$info['query']) = explode('?',$anchor,2);
		}
		if(false !== strpos($anchor,'@')) { // 解析域名
			list($anchor,$host)    =   explode('@',$anchor, 2);
		}
	}elseif(false !== strpos($url,'@')) { // 解析域名
		list($url,$host)    =   explode('@',$info['path'], 2);
	}
	// 解析子域名
	if(isset($host)) {
		$domain = $host.(strpos($host,'.')?'':strstr($_SERVER['HTTP_HOST'],'.'));
	}elseif($domain===true){
		$domain = $_SERVER['HTTP_HOST'];
		if(C('APP_SUB_DOMAIN_DEPLOY') ) { // 开启子域名部署
			$domain = $domain=='localhost'?'localhost':'www'.strstr($_SERVER['HTTP_HOST'],'.');
			// '子域名'=>array('项目[/分组]');
			foreach (C('APP_SUB_DOMAIN_RULES') as $key => $rule) {
				if(false === strpos($key,'*') && 0=== strpos($url,$rule[0])) {
					$domain = $key.strstr($domain,'.'); // 生成对应子域名
					$url    =  substr_replace($url,'',0,strlen($rule[0]));
					break;
				}
			}
		}
	}

	// 解析参数
	if(is_string($vars)) { // aaa=1&bbb=2 转换成数组
		parse_str($vars,$vars);
	}elseif(!is_array($vars)){
		$vars = array();
	}
	if(isset($info['query'])) { // 解析地址里面参数 合并到vars
		parse_str($info['query'],$params);
		$vars = array_merge($params,$vars);
	}

	// URL组装
	$depr = C('URL_PATHINFO_DEPR');
	if($url) {
		if(0=== strpos($url,'/')) {// 定义路由
			$route      =   true;
			$url        =   substr($url,1);
			if('/' != $depr) {
				$url    =   str_replace('/',$depr,$url);
			}
		}else{
			if('/' != $depr) { // 安全替换
				$url    =   str_replace('/',$depr,$url);
			}
			// 解析分组、模块和操作
			$url        =   trim($url,$depr);
			$path       =   explode($depr,$url);
			$var        =   array();
			$var[C('VAR_ACTION')]       =   !empty($path)?array_pop($path):ACTION_NAME;
			$var[C('VAR_MODULE')]       =   !empty($path)?array_pop($path):MODULE_NAME;
			if($maps = C('URL_ACTION_MAP')) {
				if(isset($maps[strtolower($var[C('VAR_MODULE')])])) {
					$maps    =   $maps[strtolower($var[C('VAR_MODULE')])];
					if($action = array_search(strtolower($var[C('VAR_ACTION')]),$maps)){
						$var[C('VAR_ACTION')] = $action;
					}
				}
			}
			if($maps = C('URL_MODULE_MAP')) {
				if($module = array_search(strtolower($var[C('VAR_MODULE')]),$maps)){
					$var[C('VAR_MODULE')] = $module;
				}
			}
			if(C('URL_CASE_INSENSITIVE')) {
				$var[C('VAR_MODULE')]   =   parse_name($var[C('VAR_MODULE')]);
			}
			if(!C('APP_SUB_DOMAIN_DEPLOY') && C('APP_GROUP_LIST')) {
				if(!empty($path)) {
					$group                  =   array_pop($path);
					$var[C('VAR_GROUP')]    =   $group;
				}else{
					if(GROUP_NAME != C('DEFAULT_GROUP')) {
						$var[C('VAR_GROUP')]=   GROUP_NAME;
					}
				}
				if(C('URL_CASE_INSENSITIVE') && isset($var[C('VAR_GROUP')])) {
					$var[C('VAR_GROUP')]    =  strtolower($var[C('VAR_GROUP')]);
				}
			}
		}
	}
	if($app=='biz'){
		$app=APP_BIZ;
	}elseif($app=='user'){
		$app=APP_USER;
	}elseif($app=='biza'){
		$app=APP_BIZADMIN;
	}elseif($app=='index'){
		$app=APP_YUNGOU;
	}elseif($app=='b2b'){
		$app=APP_B2B;
	}elseif($app=='b2buser'){
		$app=APP_B2BUSER;
	}else{
		$app=__APP__;
	}
	if(C('URL_MODEL') == 0) { // 普通模式URL转换
		$url        =   $app.'?'.http_build_query(array_reverse($var));
		if(!empty($vars)) {
			$vars   =   urldecode(http_build_query($vars));
			$url   .=   '&'.$vars;
		}
	}else{ // PATHINFO模式或者兼容URL模式
		if(isset($route)) {
			$url    =   $app.'/'.rtrim($url,$depr);
		}else{
			$url    =   $app.'/'.implode($depr,array_reverse($var));
		}
		if(!empty($vars)) { // 添加参数
			foreach ($vars as $var => $val){
				if('' !== trim($val))   $url .= $depr . $var . $depr . urlencode($val);
			}
		}
		if($suffix) {
			$suffix   =  $suffix===true?C('URL_HTML_SUFFIX'):$suffix;
			if($pos = strpos($suffix, '|')){
				$suffix = substr($suffix, 0, $pos);
			}
			if($suffix && '/' != substr($url,-1)){
				$url  .=  '.'.ltrim($suffix,'.');
			}
		}
	}
	if(isset($anchor)){
		$url  .= '#'.$anchor;
	}
	if($domain) {
		$url   =  (is_ssl()?'https://':'http://').$domain.$url;
	}
	if($redirect) // 直接跳转URL
		redirect($url);
	else
		return $url;
}


/**
 * 数组变成字符串
 * @param array $arr 数组
 * @param string $field 数组的合并字段
 * @param string $split 分割字符串
 *@date 2013-6-17
 *@time 下午6:31:22
 */
function arr_to_explode($arr=array(),$field='id',$split='') {
//数组变成字符串
	if(empty($arr)||!is_array($arr)) return false;
	$str=array();
	foreach ($arr as $v){
		$str[]=$v[$field];
	}
	if($split!=''){
		$str=implode($split, $str);
	}
	return $str;
}//end arr_to_explode

/**
 *获取角色的价格
 * @date 2013-8-8
 * @time 下午4:31:30
 * @param string $role 角色字串
 * @param unknown $price 价格数组
 * @return string | int 有价格时返回角色的价格，无价格返回价格字段名
 */
function role_price($role='',$price=array()) {
//获取角色的价格
	$myprice='';
	$role=explode(',', $role);
	if(array_intersect($role,array(3,4,5,6,7))){
		$myprice='jiasi';
	}
	if(array_intersect($role,array(8))){
		$myprice='jiasan';
	}
	if(array_intersect($role,array(2,10,11,12,13,14,9,16,17,20))){
		$myprice='jiaer';
	}
	if(array_intersect($role,array(1,15))){
		$myprice='jiayi';
	}
	if($price){
		$myprice=$price[$myprice];
	}
	return $myprice;
}//end role_price

/**
 * 给用户发短信
 * @param number $userid
 * @param string $msg
 * @return boolean
 */
function user_send_msg($userid=0,$msg='') {
	if($userid==0||$msg==''){
		return false;
	}
	$dao=M('User');
	$userinfo=$dao->field('mobile')->find($userid);
	if(empty($userinfo['mobile'])){
		return false;
	}
	$mbmsgct = mb_convert_encoding($msg,"GBK", "UTF-8");
	linuxSendMobiMsg($userinfo['mobile'],$mbmsgct);
	return true;
}

/**
 * 获得二维码图片地址
 * @param string $url 页面地址
 * @param string $site 是否是站点地址
 */
function getqr($url='',$site=FALSE) {
	$domain='http://www.91yungou.com/qr.php';
	$image='';
	if($url){
		if($site&&strpos($url,'/')===false){
			$image=$domain.'?a=site&dom='.$url;
		}else{
			$url='http://'.$_SERVER['HTTP_HOST'].$url;
			$url=myencode($url);
			$image=$domain.'?a=url&decode=1&url='.$url;
		}
		return $image;
	}
}